<template>
	<view class="container" :style="'padding-top:' + (height + 44) + 'px'">
		<view class="header" :style="'padding-top:' + height + 'px'">
			<uni-icons type="left" size="26" class="icon back" @click="backHome" :style="'top:' + (Number(height) + 10) + 'px'"></uni-icons>
			<view>{{ examName }}</view>
		</view>
		<view class="nav">
			<view class="nav_item">
				<view>{{ current + 1 }}/{{ topicTotal }}</view>
				<view>答题进度</view>
			</view>
			<view class="nav_item">
				<view>{{ correctNum }}</view>
				<view>答对数量</view>
			</view>
			<view class="nav_item">
				<view>{{ errorNum }}</view>
				<view>答错数量</view>
			</view>
		</view>
		<view class="content">
			<view class="prompt">
				<view class="prompt_type">{{ multipleChoice ? "多" : "单" }}选题</view>
				<view class="prompt_time">{{ times }}s 下一题</view>
			</view>
			<view class="topic" v-if="topicList.length">
				<view class="topic_title">{{ current + 1 }}、{{ topicList[current].questionName }}</view>
				<view class="list">
					<view class="item" v-for="itemTwo in topicList[current].option" :key="itemTwo.key" @tap="select(itemTwo)">
						<image v-if="topicSelect.includes(itemTwo.key)" :src="url + 'icon-13.png'" mode=""></image>
						<image v-else :src="url + 'icon-12.png'" mode=""></image>
						<view class="daan"><view>{{ itemTwo.key }}</view>、<view>{{ itemTwo.value }}</view></view>
					</view>
				</view>
			</view>
			<view class="confirm" v-if="topicSelect.length != 0" @tap="submit">确认</view>
		</view>
		<view class="correctAnswer" v-if="isSubmit">正确答案：{{ topicList[current].correctAnswer }}</view>
		<view class="nextQuestion" v-if="isSubmit">
			<view @tap="nextQuestion" :class="flay?'':'hui'">{{ current + 1 == topicTotal ? "查看考试结果" : "下一题" }}</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref ,nextTick} from "vue";
import { onShow, onLoad, onHide, onBackPress } from "@dcloudio/uni-app";
import api from "@/api";

const url = ref("https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/"); //图片前缀
const topicTotal = ref<number>(0); //考试题目总数量
const correctNum = ref<number>(0); //答对的考试题目数量
const errorNum = ref<number>(0); //答错的题目
const examScores = ref<number>(0); //当前答对的题目分数

const current = ref<number>(0); //轮播图
const examId = ref<string>(""); //考试id

onLoad((e) => {
	examId.value = e.id;
});
onShow(async () => {
	clearInterval(timesOut.value);
	await getRectInfo();
	await examInfo();
	await startExam();
	await examQuestionList();
	flay.value = true
	await countdown(answerTime.value);
});
onHide(() => {
	clearInterval(timesOut.value);
});
const backHome = () => {
	uni.showModal({
		title: "确定结束考试吗？",
		content: "您尚未完成考试，此时退出将结束考试",
		success: async (res) => {
			if (res.confirm) {
				clearInterval(timesOut.value);
				const res: any = await api({
					method: "get",
					url: `/mall/exam/exam-record/info/${examRecordId.value}`
				});
				if (res) {
					uni.navigateBack({
						delta: 2
					});
				}
			}
		}
	});
};

const statusBarHeight = ref(0);
const height = ref(0);
const getRectInfo = async () => {
	// 获取状态栏高度
	const sysInfo = uni.getSystemInfoSync();
	statusBarHeight.value = sysInfo.statusBarHeight;
	// 默认高度
	height.value = statusBarHeight.value;
	// #ifndef APP || H5
	// 判断获取微信小程序胶囊API是否可用 H5出现为true情况无法使用
	if (uni.canIUse("getMenuButtonBoundingClientRect")) {
		// 获取微信小程序胶囊布局位置信息
		const menuButtonRect = uni.getMenuButtonBoundingClientRect();
		// (胶囊上部高度-状态栏高度)*2 + 胶囊高度 = 导航栏高度（不包含状态栏）
		// 以此保证胶囊位于中间位置，多机型适配
		const navBarHeight = (menuButtonRect.top - sysInfo.statusBarHeight) * 2 + menuButtonRect.height;
		// 状态栏高度 + 导航栏高度 = 自定义导航栏高度总和
		height.value = navBarHeight;
	}
	// #endif
};

//考试配置
const examName = ref("");
const examInfo = async () => {
	const res: any = await api({
		method: "get",
		url: `/mall/exam/info/${examId.value}`
	});
	if (res) {
		answerTime.value = res.data.answerTime;
		examName.value = res.data.examName;
	}
};

//开始考试
const examRecordId = ref(""); //当前珍这场考试的记录id
const startExam = async () => {
	const res: any = await api({
		method: "post",
		url: `/mall/exam/exam-record/startExam`,
		data: { examId: examId.value }
	});
	if (res) {
		examRecordId.value = res.data;
	}
};
//获取题目
const topicList = ref([]); //题目列表
const topicSelect = ref([]); //当前所答题目
const multipleChoice = ref<number>(0); // 0 单选  1多选
const examQuestionList = async () => {
	const res: any = await api({
		method: "get",
		url: `/mall/exam/exam-record-question/getExamRecordQuestionList`,
		data: { examRecordId: examRecordId.value }
	});
	if (res) {
		res.data.forEach((item) => {
			item.option = formatDynamicOptions(item);
		});
		topicList.value = res.data;
		topicTotal.value = topicList.value.length;
		multipleChoice.value = topicList.value[0].type;
	}
};

//选中题目
const select = (item: any) => {
	if (isSubmit.value) return;
	if (multipleChoice.value) {
		//多选
		if (topicSelect.value.includes(item.key)) {
			topicSelect.value = topicSelect.value.filter((i) => {
				return i != item.key;
			});
		} else {
			topicSelect.value.push(item.key);
		}
	} else {
		//单选
		topicSelect.value = item.key == topicSelect.value[0] ? [] : [item.key];
	}
};

//当前题目确定，提交
const flay = ref(true)
const isSubmit = ref(false); //是否点击确定  false 未点击  true 已经提交
const submit = async () => {
	if (isSubmit.value) return;
	isSubmit.value = true;
	flay.value = false
	clearInterval(timesOut.value);
	topicSelect.value.sort();
	let isCorrect = topicSelect.value.join(",") == topicList.value[current.value].correctAnswer;
	let res: any = await api({
		method: "post",
		url: `/mall/exam/exam-record-question/update`,
		data: {
			id: topicList.value[current.value].id,
			userAnswer: topicSelect.value.join(","),
			userScore: isCorrect ? topicList.value[current.value].scoreValue : 0
		}
	});
	if (res) {
		if (isCorrect) {
			correctNum.value += 1;
		} else {
			errorNum.value += 1;
		}
		flay.value = true
		countdown(10);
	}
};

//下一题
const nextQuestion = async() => {
	if(!flay.value) return
	clearInterval(timesOut.value);
	nextTick(()=>{
		if (current.value + 1 == topicTotal.value) {
			uni.redirectTo({
				url: "/pages/businessSchool/examResults/index?examRecordId=" + examRecordId.value + "&examId=" + examId.value
			});
		} else {
			topicSelect.value = [];
			isSubmit.value = false;
			current.value += 1;
			multipleChoice.value = topicList.value[current.value].type;
			countdown(answerTime.value);
		}
		flay.value = true
	})
};

//倒计时
const answerTime = ref<number>(0); //轮播图倒计时
const times = ref<number>(0); //倒计时
let timesOut = ref(null); //定时器
const countdown = async (num: number) => {
	clearInterval(timesOut.value);
	times.value = num;
	timesOut.value = setInterval(async () => {
		if (times.value <= 0) {
			clearInterval(timesOut.value);
			if (isSubmit.value) {
				await nextQuestion();
			} else {
				await submit();
			}
		} else {
			times.value--;
		}
	}, 1000);
};
//处理题目
const formatDynamicOptions = (data) => {
	const options = [];
	Object.keys(data).forEach((key) => {
		if (key.startsWith("option")) {
			const optionKey = key.replace("option", ""); // 提取选项字母
			const optionValue = data[key];
			if (optionValue !== null && optionValue !== undefined) {
				options.push({
					key: optionKey, // 选项字母（如 A、B、C）
					value: optionValue // 选项内容
				});
			}
		}
	});
	return options;
};
</script>

<style lang="scss" scoped>
.container {
	width: 100vw;
	min-height: 100vh;
	line-height: 1;
	overflow-y: scroll;
	padding-top: calc(var(--status-bar-height) + 88rpx);
	padding-bottom: calc(var(--safe-area-bottom) + 188rpx);
	background-color: #f9f6f6;
}

.header {
	position: fixed;
	left: 0;
	top: 0;
	width: 100vw;
	height: 88rpx;
	font-size: 36rpx;
	color: #1b2120;
	background-color: #fff;
	@include flex(center, center);

	.back {
		position: absolute;
		left: 32rpx;
	}
}

.nav {
	width: 100%;
	margin-bottom: 24rpx;
	padding: 20rpx 32rpx;
	box-sizing: border-box;
	background-color: #ffffff;
	@include flex(center, space-between);

	.nav_item {
		width: 218rpx;
		height: 134rpx;
		padding-top: 32rpx;
		background: #eff6ff;
		border-radius: 16rpx;
		box-sizing: border-box;

		view {
			width: 100%;
			color: #5c5e5e;
			font-size: 24rpx;
			text-align: center;

			&:first-child {
				margin-bottom: 16rpx;
				font-weight: bold;
				font-size: 30rpx;
				color: #1b2120;
			}
		}

		&:nth-child(2) {
			background: #ebfff6;
		}

		&:nth-child(3) {
			background: #fff1f4;
		}
	}
}

.content {
	width: 686rpx;
	background: #ffffff;
	border-radius: 24rpx;
	margin-left: 32rpx;
	padding: 40rpx 32rpx;
	box-sizing: border-box;

	.prompt {
		margin-bottom: 40rpx;
		@include flex(center, space-between);

		.prompt_type {
			color: #ff6084;
			font-size: 22rpx;
			padding: 8rpx 14rpx;
			background: #fce6eb;
			border-radius: 32rpx;
		}

		.prompt_time {
			color: #ff6084;
			font-size: 24rpx;
		}
	}
	.topic {
		width: 100%;
		color: #1b2120;
		font-size: 28rpx;
		line-height: 28rpx;
		box-sizing: border-box;

		.topic_title {
			font-weight: bold;
			font-size: 32rpx;
			line-height: 48rpx;
			margin-bottom: 40rpx;
		}

		.item {
			@include flex(center);
			margin-bottom: 16rpx;
			padding: 32rpx 24rpx;
			border-radius: 16rpx;
			border: 2rpx solid #f5f6f7;

			&:last-child {
				margin: 0;
			}
			.daan{
				width: calc(100% - 40rpx - 32rpx);
				@include flex(center);
				view{
					line-height: 38rpx;
					&:last-child{
						width: calc(100% - 28rpx);
					}
				}
			}
		}

		image {
			width: 40rpx;
			height: 40rpx;
			margin-right: 32rpx;
		}
	}

	.confirm {
		width: 376rpx;
		height: 72rpx;
		color: #ffffff;
		font-size: 26rpx;
		border-radius: 62rpx;
		margin: 40rpx auto 0;
		@include flex(center, center);
		background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
	}
}

.correctAnswer {
	width: 686rpx;
	height: 116rpx;
	color: #1b2120;
	font-size: 36rpx;
	font-weight: bold;
	background: #fef0f3;
	border-radius: 16rpx;
	margin: 16rpx 0 0 32rpx;
	@include flex(center, center);
}

.nextQuestion {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100vw;
	padding: 8rpx 32rpx;
	padding-bottom: calc(var(--safe-area-bottom) + 4rpx);
	box-sizing: border-box;
	background-color: #ffffff;

	view {
		width: 100%;
		height: 88rpx;
		color: #ffffff;
		font-size: 28rpx;
		border-radius: 62rpx;
		@include flex(center, center);
		background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
	}
	.hui{
		background: linear-gradient( 90deg, #FFA6BC 0%, #FFA3A3 100%);
	}
}
</style>
